package com.shujia

import scala.collection.immutable
import scala.io.{BufferedSource, Source}

object Demo19WordCountScala {
  def main(args: Array[String]): Unit = {
    // 1、读取文件
    val br: BufferedSource = Source.fromFile("Scala/data/words.txt")


    // 2、切分每一行数据 提取每个单词
    val words: List[String] =
      br.getLines()
        .toList
        .flatMap(line => {
          line.split(",")
        })

    // 3、按照单词分组
    val groupWords: Map[String, List[String]] = words.groupBy(w => w)

    // 4、统计单词数量
    val wordCount: Map[String, Int] = groupWords.map {
      case (word: String, wordsList: List[String]) =>
        (word, wordsList.length)
    }

    // 5、打印结果
    wordCount.foreach(println)

    // 链式调用
    Source
      .fromFile("Scala/data/words.txt")
      .getLines()
      .toList
      .flatMap(_.split(","))
      .groupBy(w => w)
      .map(kv => (kv._1, kv._2.length))
      .foreach(println)







    // 关闭文件
    br.close()


  }

}
